#include "main.h"
#include "io.h"
#include <stdarg.h>
#include "chprintf.h"
#include "rficonsole.h"

/*
 * @brief  Configures EXTI Line0 (connected to PA0 pin) in interrupt mode
 * @param  None
 * @retval None
 */
EXTI_InitTypeDef EXTI_InitStructure;

void EXTILine_Config(uint32_t GPIO_Pin, uint8_t EXTI_PinSourcex,
		uint32_t EXTI_Line, uint8_t NVIC_IRQChannel) {

//	GPIO_InitTypeDef GPIO_InitStructure;
//	NVIC_InitTypeDef NVIC_InitStructure;

//	/* Enable GPIOA clock */
//	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
//	/* Enable SYSCFG clock */
//	RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);

//	/* Configure pin as input floating */
//	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
//	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
//	GPIO_InitStructure.GPIO_Pin = GPIO_Pin;
//	GPIO_Init(GPIOA, &GPIO_InitStructure);

	/* Connect EXTI Line to pin */
	SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA, EXTI_PinSourcex);

	/* Configure EXTI Line */
	EXTI_InitStructure.EXTI_Line = EXTI_Line;
	EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
	EXTI_InitStructure.EXTI_LineCmd = ENABLE;
	EXTI_Init(&EXTI_InitStructure);

//	/* Enable and set EXTI Line Interrupt to the lowest priority */
//	NVIC_InitStructure.NVIC_IRQChannel = NVIC_IRQChannel;
//	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x01;
//	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x01;
//	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
//	NVIC_Init(&NVIC_InitStructure);
}

void EXTILine3_Config() {
	EXTILine_Config(GPIO_Pin_3, EXTI_PinSource3, EXTI_Line3, EXTI3_IRQn);
}

inline void turnPinOff(GPIO_TypeDef *IO, uint32_t pinBit) {
	IO->BSRRH = pinBit;
}

inline void turnPinOn(GPIO_TypeDef *IO, uint32_t pinBit) {
	IO->BSRRL = pinBit;
}

void setPinValue(GPIO_TypeDef *IO, uint32_t pinNumber, int on) {
	if (on)
		turnPinOn(IO, PAL_PORT_BIT(pinNumber) );
	else
		turnPinOff(IO, PAL_PORT_BIT(pinNumber) );
}


